<template>
  <div class="about">
    <div style="background: aliceblue;width: 700px;padding: 30px 50px;margin: 100px auto;">
      <h1 style="text-align: center;margin-bottom: 30px;">管理员登录</h1>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密  码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style>
  body {
    background: #2c3e50;
  }
</style>


<script>
export default {
  data() {
    return {
      ruleForm: {
        username:'root',
        password:'123456'
      },
      rules: {
        /*trigger表示检查什么情况会触发，blur表示当控件丢失焦点时触发检查*/
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 4, max: 15, message: '用户名必须在 4 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 4, max: 15, message: '密码的长度必须在 4 到 15 个字符', trigger: 'blur'}
        ],
      }
    };
  },
  methods: {
    submitForm(formName) {
      /*此处是在提交表单时再次检擦所有规则*/
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = "http://localhost:15723/admins/login";
          var s = this.qs.stringify(this.ruleForm);
          this.axios.post(url,s).then((response)=>{
            let jsonResult = response.data;
            if(jsonResult.state == 20000){
              this.$message({
                message: '登录成功！',
                type: 'success'
              });
              console.log(jsonResult.data);
              //localStorage方法相当于将一些需要存放的信息以键值对的形式存放在本地中，并且当前创建的localStorage是只服务于此网站的
              localStorage.setItem("jwt",jsonResult.data);
              console.log("从本地存储中获取的键值对信息:"+localStorage.getItem("jwt"));
              this.$router.push('/');
            }else if(jsonResult.state = 40100){
              this.$message.error(jsonResult.message);
            }else if(jsonResult.state == 40101){
              //账号状态出现错误
              this.$alert(jsonResult.message, '登录失败', {
                confirmButtonText: '确定',
                callback: action => {}
              });
            }else{
              //出现了其他错误
              this.$alert(jsonResult.message, '登录失败', {
                confirmButtonText: '确定',
                callback: action => {}
              });
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>
